package com.linjiahao.nettyGateway.filter;

import com.linjiahao.commonUtil.base.JWTUtil;
import com.linjiahao.commonall.constant.AuthConstant;
import com.linjiahao.nettyGateway.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName WebsocketFilter
 * @Description: 在WebsocketRoutingFilter之前进行鉴权
 * @Author linjiahao
 * @Date 2023/1/12
 **/
@Component
@Slf4j
public class WebsocketFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        URI requestUrl = (URI)exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
        String scheme = requestUrl.getScheme();
        log.info("gateway-》"+WebsocketFilter.class+"连接转发协议为：{}",scheme);
        if(Constant.WS_PROTOCOL.equals(scheme) || Constant.WSS_PROTOCOL.equals(scheme)){
            ServerHttpRequest request = exchange.getRequest();
            HttpHeaders headers = request.getHeaders();
            List<String> protocols = headers.get(AuthConstant.SUB_PROTOCOL);
            if (protocols != null) {
                protocols = (List)headers.get("Sec-WebSocket-Protocol").stream().flatMap((header) -> {
                    return Arrays.stream(StringUtils.commaDelimitedListToStringArray(header));
                }).map(String::trim).collect(Collectors.toList());
            }
            String token = protocols.get(0);
            log.info("连接协议"+AuthConstant.SUB_PROTOCOL+"为:{}", token);
            String userId = JWTUtil.getUserIdofSring(token);
            ServerHttpRequest build = exchange.getRequest().mutate().headers(wssheaders -> {
                wssheaders.add(AuthConstant.AUTH_HEADER, userId);
            }).build();
            ServerWebExchange wssExchange = exchange.mutate().request(build).build();
            return chain.filter(wssExchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 2;
    }

}
